package be.jprojects.subscription.dataaccess.mysql;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import be.jprojects.subscription.dataaccess.PersonDataAccess;
import be.jprojects.subscription.logic.Person;
import be.jprojects.subscription.logic.interfaces.IPerson;

public class MySQLPersonDataAccess implements PersonDataAccess{
	private MySQLDataAccessObjectFactory mySQLDataAccessObjectFactory;
	
	public MySQLPersonDataAccess(MySQLDataAccessObjectFactory mySQLDataAccessObjectFactory) {
		setMySQLDataAccessObjectFactory(mySQLDataAccessObjectFactory);
	}

	public MySQLDataAccessObjectFactory getMySQLDataAccessObjectFactory() {
		return mySQLDataAccessObjectFactory;
	}

	public void setMySQLDataAccessObjectFactory(
			MySQLDataAccessObjectFactory mySQLDataAccessObjectFactory) {
		this.mySQLDataAccessObjectFactory = mySQLDataAccessObjectFactory;
	}

	@Override
	public boolean deletePerson(IPerson person) throws Exception {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public IPerson findPerson() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<IPerson> getPersons() throws Exception {
		Connection c = mySQLDataAccessObjectFactory.getConnection();
		PreparedStatement pStatement = c.prepareStatement(mySQLDataAccessObjectFactory.getBundle().getString("getPersons"));
		ResultSet rSet = pStatement.executeQuery();
		List<IPerson> l = new ArrayList<IPerson>();
		while (rSet.next()) {
			l.add(mapPerson(rSet));
		}
		return l;
	}

	@Override
	public int insertPerson(IPerson person) throws Exception {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public boolean updatePerson(IPerson person) throws Exception{
		// TODO Auto-generated method stub
		return false;
	}
	
	private IPerson mapPerson(ResultSet set) throws SQLException {
		IPerson p = new Person();
		p.setPersonID(set.getInt(mySQLDataAccessObjectFactory.getBundle().getString("personid")));
		p.setFirstName(set.getString(mySQLDataAccessObjectFactory.getBundle().getString("firstname"))); 
		p.setLastName(set.getString(mySQLDataAccessObjectFactory.getBundle().getString("lastname")));
		p.setMiddleName(set.getString(mySQLDataAccessObjectFactory.getBundle().getString("middlename")));
		return p;
	}

}
